<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function binary_search(arr, target) {
        let low = 0; //设定下标
        let high = arr.length - 1; //设定上标
        //判断一下最大或者最小是否超出范围
        if(arr[low]>target || arr[high] < target){
            return -1;
        }
        //判断两次Mid数是否一样,如果一样就返回false
        let tmp_mid = -1;
        while (true) {
            let mid = Math.floor((low + high) / 2); //二分查找的关键
            if (arr[mid] > target) {
                high = mid;
            } else if (arr[mid] < target) {
                low = mid;
            } else {
                return mid
            }
            if(tmp_mid === mid){
                return -1;
            }
            tmp_mid =mid;
        }
    }


    let arr =[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];
    // high = 2 low = 0 target为4
    //1. mid为1 取3 | 3<4 所以 low=1,high=2
    //2. mid为1 取3 | 3<4 所以 low=1,high=2

    let res = binary_search(arr,23);

    console.log(res);

</script>
</body>
</html>